package com.china08.yxyapi.api.manage.tec.teaching.lecture.res;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserFavor;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.mg.YxyUserFavorRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureResRepository;
import com.china08.yxyapi.service.yxyresource.YxyResourceLectureService;
import com.china08.yxyapi.util.YxyResUtil;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--添加备授课资源
 * 
 */
@CrossOrigin
@RestController
public class ResController extends YxyApiBaseController {

    @Autowired
    private YxyResUtil YxyResUtil;

    @Autowired
    private YxyResourceLectureService yrs;

    @Autowired
    private YxyLectureResRepository yxyLectureResRepository;

    @Autowired
    private YxyResResourceRepository YxyResResourceRepository;

    @Autowired
    private YxyResBookRepository yrbr;

    @Autowired
    private YxyUserFavorRepository favorRepository;

    @Autowired
    private ElasticsearchTemplate et;

    @ApiOperation(value = "选入资源查询")
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/res", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> find(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqModel reqModel) throws IllegalAccessException, InvocationTargetException {
        Page<RespModel> respPage = null;

        String resVip = getProfile(request, response).getResVip();
        String schoolId = getProfile(request, response).getSchoolId();
        String userId = getProfile(request, response).getId();
        String condition = reqModel.condition;
        String vipCondition = reqModel.vipCondition;
        boolean jingRes = reqModel.jingRes;
        String keyword = reqModel.keyword;
        String bookcontent = reqModel.bookcontent;
        Sort sort = new Sort(Direction.DESC, condition);
        // ## pageable
        Pageable pageable = null;
        pageable = new PageRequest(reqModel.page, reqModel.size, sort);
        // 我的收藏
        Sort sortMy = new Sort(Direction.DESC, "createdDate");
        Pageable pageableMy = new PageRequest(reqModel.page, reqModel.size, sortMy);

        List<RespModel> list = new ArrayList<ResController.RespModel>();
        YxyResBook book = yrbr.findById(reqModel.bookId);
        String phase = book.getPhaseId();
        String subject = book.getSubjectId();
        String version = book.getVersionId();
        String semester = book.getSemersterId();
        Page<ElasticYxyResResource> page = null;

        // 查询子目录
        YxyResUtil resUtil = new YxyResUtil();
        List<String> parent = resUtil.findTocByTocParent(bookcontent);
        int size = parent.size();
        String[] bookContent = parent.toArray(new String[size]);

        Page<YxyUserFavor> pageMy = null;
        if (reqModel.resType == 1) {
            page = yrs.lectureResourceArea(jingRes, vipCondition, reqModel.areaId, reqModel.resType, phase, subject,
                    version, bookcontent, semester, reqModel.bookId, reqModel.type, reqModel.format, keyword,
                    Type.PHRASE, pageable);
        } else if (reqModel.resType == 2) {
            page = yrs.lectureResourceSchool(jingRes, vipCondition, schoolId, reqModel.resType, phase, subject, version,
                    bookcontent, semester, reqModel.bookId, reqModel.type, reqModel.format, keyword, Type.PHRASE,
                    pageable);
        } else if (reqModel.resType == 3) {
            page = yrs.lectureResourceYun(jingRes, vipCondition, reqModel.resType, phase, subject, version, bookcontent,
                    semester, reqModel.bookId, reqModel.type, reqModel.format, keyword, Type.PHRASE, pageable);
        } else if (reqModel.resType == 4) {
            page = yrs.lectureResourceMy(jingRes, vipCondition, userId, schoolId, reqModel.resType, phase, subject,
                    version, bookcontent, semester, reqModel.bookId, reqModel.type, reqModel.format, keyword,
                    Type.PHRASE, pageable);
        } else if (reqModel.resType == 5) {
            if (StringUtils.isNotBlank(keyword)) {
                if (bookcontent == null) {
                    pageMy = favorRepository.findByUserIdAndSemesterIdAndResNameContaining(userId, semester, keyword,
                            pageableMy);
                } else {
                    pageMy = favorRepository.findByUserIdAndBookContentIdInAndResNameContaining(userId, bookContent,
                            keyword, pageableMy);
                }
            } else {
                if (bookcontent == null) {
                    pageMy = favorRepository.findByUserIdAndSemesterId(userId, semester, pageableMy);
                } else {
                    pageMy = favorRepository.findByUserIdAndBookContentIdIn(userId, bookContent, pageableMy);
                }
            }
        }
        long totle = 0l;
        if (reqModel.resType != 5) {
            // 备课包
            if (page != null) {
                totle = page.getTotalElements();
                for (ElasticYxyResResource elasticYxyResResource : page) {
                    RespModel model = new RespModel();
                    BeanUtils.copyProperties(model, elasticYxyResResource);
                    String download = YxyResUtil.getDownloadUrl(elasticYxyResResource.getId());
                    model.setDownloadLocation(download);
                    String resEsId = elasticYxyResResource.getId();
                    String extension = elasticYxyResResource.getExtension();
                    String typeId = elasticYxyResResource.getTypeId();
                    Integer countChk = yxyLectureResRepository
                            .countBySchoolIdAndUserIdAndBookcontentsIdAndResourceIdAndIsDeleteNot(schoolId, userId,
                                    reqModel.packbookContent, resEsId, 1);
                    model.mark = elasticYxyResResource.getMark() == 0 ? 5
                            : new BigDecimal(elasticYxyResResource.getMark()).setScale(1, BigDecimal.ROUND_HALF_UP)
                                    .floatValue();
                    if (countChk > 0) {
                        // 是否已经存在于备课资源
                        model.ifOpt = 1;
                    }
                    model.setPreview(YxyResUtil.getPreviewUrl(resEsId));
                    YxyResResource findById = YxyResResourceRepository.findById(elasticYxyResResource.getId());
                    Integer fileSize = findById.getFileSize();
                    if (null != fileSize) {
                        Double valueOf = Double.valueOf(fileSize + "");
                        Double file = valueOf / 1024;
                        BigDecimal bg = new BigDecimal(file);
                        double f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                        model.fileSize = f1;
                    } else {
                        model.fileSize = 0;
                    }
                    model.extension = extension;
                    model.typeId = typeId;
                    if (schoolId.equals("ff80808142a16af00142a1a60f010006")
                            || "ff80808142a16af00142a1a60f010006".equals(elasticYxyResResource.getShoolId())) {
                        model.uploaderSchoolName = "";
                    }
                    model.vip = elasticYxyResResource.getIsVip();
                    model.isHighQualityYx = elasticYxyResResource.getIsHighQualityYx();
                    model.userVip = resVip;
                    model.status = elasticYxyResResource.getStatus();
                    list.add(model);
                }
            }
            respPage = new PageImpl<>(list, pageable, totle);
        } else {
            if (pageMy != null) {
                totle = pageMy.getTotalElements();
                for (YxyUserFavor userFavor : pageMy) {
                    RespModel model = new RespModel();
                    GetQuery getQuery = new GetQuery();
                    getQuery.setId(userFavor.getResId());
                    ElasticYxyResResource elasticYxyResResource = et.queryForObject(getQuery,
                            ElasticYxyResResource.class);
                    String download = YxyResUtil.getDownloadUrl(elasticYxyResResource.getId());
                    model.setDownloadLocation(download);
                    String resEsId = elasticYxyResResource.getId();
                    String extension = elasticYxyResResource.getExtension();
                    String typeId = elasticYxyResResource.getTypeId();
                    Integer countChk = yxyLectureResRepository
                            .countBySchoolIdAndUserIdAndBookcontentsIdAndResourceIdAndIsDeleteNot(schoolId, userId,
                                    reqModel.packbookContent, resEsId, 1);
                    model.mark = elasticYxyResResource.getMark() == 0 ? 5
                            : new BigDecimal(elasticYxyResResource.getMark()).setScale(1, BigDecimal.ROUND_HALF_UP)
                                    .floatValue();
                    model.status = elasticYxyResResource.getStatus();
                    if (countChk > 0) {
                        // 是否已经存在于备课资源
                        model.ifOpt = 1;
                    }
                    model.setPreview(YxyResUtil.getPreviewUrl(resEsId));
                    Integer fileSize = elasticYxyResResource.getFileSize();
                    if (null != fileSize) {
                        Double valueOf = Double.valueOf(fileSize + "");
                        Double file = valueOf / 1024;
                        BigDecimal bg = new BigDecimal(file);
                        double f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                        model.fileSize = f1;
                    } else {
                        model.fileSize = 0;
                    }
                    model.extension = extension;
                    model.typeId = typeId;
                    model.title = elasticYxyResResource.getTitle();
                    model.uploaderName = elasticYxyResResource.getUploaderName() == null ? "云校"
                            : elasticYxyResResource.getUploaderName();
                    model.id = elasticYxyResResource.getId();
                    model.formatId = elasticYxyResResource.getFormatId();
                    model.location = elasticYxyResResource.getLocation();
                    if (schoolId.equals("ff80808142a16af00142a1a60f010006")
                            || "ff80808142a16af00142a1a60f010006".equals(elasticYxyResResource.getShoolId())) {
                        model.uploaderSchoolName = "";
                    } else {
                        model.uploaderSchoolName = elasticYxyResResource.getUploaderSchoolName();
                    }
                    model.vip = elasticYxyResResource.getIsVip();
                    model.isHighQualityYx = elasticYxyResResource.getIsHighQualityYx();
                    model.userVip = resVip;
                    model.pv = elasticYxyResResource.getPv();
                    list.add(model);
                }
            }

            respPage = new PageImpl<>(list, pageableMy, totle);
        }

        return respPage;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        // 1区域资源 2本校资源 3云校资源 4 我的资源 5 我的收藏
        public Integer resType = 1;
        // 筛选条件 uploadTime-最新 mark-评分 pv-浏览
        public String condition;
        // VIP筛选条件 no- 所有资源 vip-vip资源 free -非VIP
        public String vipCondition;
        // 精品资源
        public boolean jingRes;
        // 域名
        public String domain;
        public String bookcontent;
        public String bookId;
        public String packbookContent;
        public String type;
        public String format;
        public String keyword;
        public String areaId;

        @Override
        public void autoCheck() {
        }

    }

    public static class RespModel extends YxyApiRespModel {
        // 资源ID
        public String id;

        // 上传人名
        public String uploaderName;

        // 上传者学校名字
        public String uploaderSchoolName;

        // 资源简介
        public String intro;

        // 标题
        public String title;

        // 下载量
        public Long downloadCount = 0l;

        // 浏览次数
        public Long pv = 0l;

        // 是否下架
        public Integer status;

        // 文件路径
        public String location;

        // 格式
        public String formatId;

        // 下载连接
        public String downloadLocation = "";

        // 资源大小
        public double fileSize;

        // vip
        public boolean vip;

        // 云校精品 0否 1是
        public Integer isHighQualityYx;

        // 用户是否为VIP
        public String userVip;

        // 预览
        public String preview = "";
        public String extension;
        public String typeId;
        public float mark;

        public float getMark() {
            return mark;
        }

        public void setMark(float mark) {
            this.mark = mark;
        }

        public String getExtension() {
            return extension;
        }

        public void setExtension(String extension) {
            this.extension = extension;
        }

        // 是否选入 0 否 1 是
        public Integer ifOpt = 0;

        public String getPreview() {
            return preview;
        }

        public void setPreview(String preview) {
            this.preview = preview;
        }

        public Integer getIfOpt() {
            return ifOpt;
        }

        public void setIfOpt(Integer ifOpt) {
            this.ifOpt = ifOpt;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUploaderName() {
            return uploaderName;
        }

        public void setUploaderName(String uploaderName) {
            this.uploaderName = uploaderName;
        }

        public String getUploaderSchoolName() {
            return uploaderSchoolName;
        }

        public void setUploaderSchoolName(String uploaderSchoolName) {
            this.uploaderSchoolName = uploaderSchoolName;
        }

        public String getIntro() {
            return intro;
        }

        public void setIntro(String intro) {
            this.intro = intro;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Long getDownloadCount() {
            return downloadCount;
        }

        public void setDownloadCount(Long downloadCount) {
            this.downloadCount = downloadCount;
        }

        public Long getPv() {
            return pv;
        }

        public void setPv(Long pv) {
            this.pv = pv;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public String getFormatId() {
            return formatId;
        }

        public void setFormatId(String formatId) {
            this.formatId = formatId;
        }

        public String getDownloadLocation() {
            return downloadLocation;
        }

        public void setDownloadLocation(String downloadLocation) {
            this.downloadLocation = downloadLocation;
        }

        public Double getFileSize() {
            return fileSize;
        }

        public void setFileSize(Double fileSize) {
            this.fileSize = fileSize;
        }

        public boolean isVip() {
            return vip;
        }

        public void setVip(boolean vip) {
            this.vip = vip;
        }

        public Integer getIsHighQualityYx() {
            return isHighQualityYx;
        }

        public void setIsHighQualityYx(Integer isHighQualityYx) {
            this.isHighQualityYx = isHighQualityYx;
        }

    }
}
